<template>
  <!--实体ID 新增策略-->
  <section class="component">
    <el-form :model="model" :rules="rules" ref="add-strategic" label-width="125px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="实体注记" prop="strategyName">
            <el-input type="input" v-model.trim="model.strategyName" :maxlength="20" :disabled="show"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="优先级" prop="priorityNo">
            <el-input type="input" class="no-number" v-model.trim="model.priorityNo" maxlength="4" :disabled="show"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="实体类型" prop="entityType">
            <el-select v-model="model.entityType" placeholder="请选择" :disabled="show">
              <el-option v-for="{ index, name, code } in $dict.getDictData('EntityType')" :key="index" :label="name" :value="code"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="实体编码" prop="entityCode">
            <el-input type="input" class="no-number" v-model.trim="model.entityCode" maxlength="4" :disabled="show"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="策略状态" prop="commonState">
            <el-select v-model="model.commonState" placeholder="请选择" :disabled="show">
              <el-option v-for="{ index, name, code } in $dict.getDictData('CommonState')" :key="index" :label="name" :value="code"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-card class="cardStyle">
            <div slot="header" class="row between-span">
              <span>设置获取数据规则</span>
              <el-button @click="addNewConfigLine" :disabled="show">增加</el-button>
            </div>
            <expression-base v-model="strategyDataSet" :entityIdStr='entityIdStr' :flag="true" :disabledData="show"></expression-base>
          </el-card>
        </el-col>
      </el-row>
      <el-row>
        <el-col class="widthMargin">
          <el-form-item label="策略注记" prop="strategyNotes">
            <el-input type="textarea" v-model.trim="model.strategyNotes" :autosize="{ minRows: 2, maxRows: 4 }" :maxlength="300" show-word-limit :disabled="show"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="history">
        <el-col :span="2" class="fontMargin">历史注记</el-col>
        <el-col class="widthMarginTwo">
          <data-box :data="approvalHistory" class="paddingNone">
            <template slot="columns">
              <el-table-column prop="timeCreated" label="注记时间" :min-width="$helper.getColumnWidth(5)" :formatter="row => $filter.dateTimeFormat(row.timeCreated)" show-overflow-tooltip>
              </el-table-column>
              <el-table-column prop="operatorRealName" label="添加人" :min-width="$helper.getColumnWidth(5)" show-overflow-tooltip>
              </el-table-column>
              <el-table-column prop="strategyNotes" label="内容" :min-width="$helper.getColumnWidth(5)" show-overflow-tooltip>
              </el-table-column>
            </template>
          </data-box>
        </el-col>
      </el-row>
      <div class="operate-buttons" v-if="show">
        <el-button @click="emitClose">关闭</el-button>
      </div>
      <div class="operate-buttons" v-else>
        <el-button @click="emitClose">取消</el-button>
        <el-button @click="submit">{{!!modifyData.id ? '提交审批' : '保存'}}</el-button>
      </div>
    </el-form>
  </section>
</template>

<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";
import { Dependencies } from "~/core/decorator";
import ExpressionBase from "./expression-base.vue";
import { IstrategyInfo } from "./strategy-helper.config";
import { Emit, Prop } from "vue-property-decorator";
import { PageService } from "~/utils/page.service";
import { EntityIdService } from "~/services/management-service/entity-id.service";
import { ValidatorService } from "~/utils/validator.service";
import { OPERATION_TYPE } from "~/config/enum.config";

@Component({
  components: {
    ExpressionBase
  }
})
export default class AddStrategic extends Vue {
  @Dependencies(EntityIdService) private entityIdService: EntityIdService;
  @Dependencies(PageService)
  private pageService: PageService;

  @Prop({
    type: Object
  })
  private modifyData: object;
  @Prop() private show;
  private entityIdStr = 'ENTITYID'
  private model: any = {
    id: '',
    strategyName: "",
    priorityNo: "", // 优先级
    entityCode: "", // 实体编码
    entityType: "", // 实体类型
    commonState: "", //策略状态
    strategyNotes: "", //策略描述
    formulaJson: "[]"
  };
  // 页面按钮类型
  private operationType: any = OPERATION_TYPE
  private history: boolean = false
  private approvalHistory: any = []
  private verification: boolean = false
  private rules: any = {
    strategyName: [{ required: true, message: "请输入策略名称", trigger: "blur" }],
    priorityNo: [{ required: true, message: "请输入优先级", trigger: "blur" }, { validator: this.validatePass }],
    entityCode: [{ required: true, message: "请输入实体编码", trigger: "blur" }, { validator: this.validatePass }],
    entityType: [{ required: true, message: "请选择实体类型", trigger: "change" }],
    strategyNotes: [{ required: true, message: "请输入实体注记", trigger: "change" }],
    commonState: [{ required: true, message: "请选择策略状态", trigger: "change" }],
  };

  @Emit("refreshData")
  public refreshData () { }
  @Emit("close")
  private emitClose () {
    this.reset()
    this.history = false
    this.model.id = "";
    this.refreshData();
  }
  /**
   * 自定义表单验证规则
   */
  private validatePass (rule: any, value: any, callback: any) {
    if (typeof (Number(value)) === 'number' && String(Number(value)) !== 'NaN') {
      value.length < 4 ? callback(new Error('长度在4个字符！')) : callback()
    } else { callback(new Error('必须是数字！')) }
  }
  private get strategyDataSet () {
    if (!this.model.formulaJson) return [];
    return JSON.parse(this.model.formulaJson) as IstrategyInfo[];
  }

  private set strategyDataSet (value) {
    this.model.formulaJson = JSON.stringify(value);
  }

  /**
   * 验证数据是否完整
   */
  private validateExpression () {
    let numLeft = 0
    let numRight = 0
    let numsLeft = 0
    let numsRight = 0
    const formula = JSON.parse(this.model.formulaJson).map(v => {
      switch (v.leftBracket) {
        case '(':
          numLeft += 1
          break;
        case '((':
          numsLeft += 1
          break;
      }
      switch (v.rightBracket) {
        case ')':
          numRight += 1
          break;
        case '))':
          numsRight += 1
          break;
      }
    })
    if (numLeft !== numRight || numsLeft !== numsRight) { return this.$message.error('请检查括号的完整性!') }
    const rules = {
      relation: { required: true, message: "请选择链接关系符" },
      variable: { required: true, message: "请选择字段" },
      symbol: { required: true, message: "请选择操作符" },
      value: { required: true, message: "缺少期望值" }
    };
    const results = this.strategyDataSet.map(v =>
      ValidatorService.validate(v, rules)
    );
    return Promise.all(results)
      .then(() => {
        this.verification = true;
        return true
      })
      .catch(({ errors }) => {
        if (errors.length) this.$message(errors[0].message);
        this.verification = false;
        return Promise.reject(false);
      });
  }

  private addNewConfigLine () {
    let addFlag = true;
    if (this.strategyDataSet.length >= 5) {
      this.$message.warning('数据规则已达最大长度!')
      return
    }
    if (this.strategyDataSet.length) {
      const lastLine = this.strategyDataSet[this.strategyDataSet.length - 1];
      addFlag = !!lastLine.relation && !!lastLine.variable && !!lastLine.symbol && !!lastLine.value;
    }
    if (addFlag) {
      this.strategyDataSet.push({
        name: '',
        relation: "",
        variable: "",
        symbol: "",
        leftBracket: "",
        rightBracket: "",
        value: ""
      });
    } else {
      this.validateExpression()
    }
  }
  /**
   * 重置
   */
  private reset () {
    const form: any = this.$refs["add-strategic"];
    form.resetFields();
    this.model = {
      id: '',
      strategyName: "",
      priorityNo: "", // 优先级
      entityCode: "", // 实体编码
      entityType: "", // 实体类型
      commonState: "", //策略状态
      strategyNotes: "", //策略描述
      formulaJson: "[]"
    };
  }
  /**
   * 提交审批
   */
  private submit () {
    const form: any = this.$refs["add-strategic"];
    form.validate(valid => {
      if (!valid) return
      if (this.model.formulaJson.length === 2) {
        this.$message.error('请设置数据规则!');
      } else {
        this.validateExpression()
        if (this.verification) {
          this.entityIdService.saveEntityId(this.model).subscribe(data => {
            this.$message.success('操作成功!');
            this.refreshData();
            this.emitClose();
            this.reset()
          })
        }
      }
    })
  }

  /**
   * 弹框打开时初始化页面信息
   */
  private refresh (modifyData) {
    this.reset();
    this.approvalHistory = []
    if (this.operationType.DEFAULT === 'OPERATION_EDIT' || this.operationType.DEFAULT === 'OPERATION_SEE') {
      this.history = true
      this.entityIdService.logEntityId(modifyData).subscribe(data => {
        data.content.map(f => {
          this.approvalHistory.push({
            'timeCreated': f.timeCreated,
            'operatorRealName': f.operatorRealName,
            'strategyNotes': f.strategyNotes
          })
        })
      })
      this.model = modifyData
    }
  }
}
</script>

<style lang="less" scoped>
.cardStyle {
  width: 630px !important;
  margin-left: 64px !important;
  box-shadow: none !important;
  border-bottom: 1px solid #ebeef5 !important;
}
.widthMargin {
  width: 696px !important;
  margin-top: 20px !important;
}
.widthMarginTwo {
  width: 571px !important;
  margin-left: -5px !important;
}
.fontMargin {
  font-size: 12px !important;
  margin-left: 65px !important;
}
.paddingNone {
  padding: 0px !important;
}
</style>
